package com.tjp.subject.domain.handler.subject;

import com.tjp.subject.common.enums.SubjectInfoTypeEnum;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: jz-club
 * @description: 题目类型工厂
 * @author: aaronTang
 * @create: 2024-02-29
 */
@Component  //交给Spring容器管理
public class SubjectTypeHandlerFactory implements InitializingBean {

    //依靠Spring的特性,注入进这个List中
    @Resource
    private List<SubjectTypeHandler> subjectTypeHandlerList;

    //建立一个map做处理  思考:工厂装载的实现方式有哪些?利弊?
    private Map<SubjectInfoTypeEnum, SubjectTypeHandler> handlerMap = new HashMap<>();


    //1.提供SubjectHandler
    public SubjectTypeHandler getHandlerType(int subjectType) {
        SubjectInfoTypeEnum subjectInfoTypeEnum = SubjectInfoTypeEnum.getByCode(subjectType);
        return handlerMap.get(subjectInfoTypeEnum);
    }


    /**
     * 该方法执行时机:初始化Bean成功后就会执行
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        for (SubjectTypeHandler subjectTypeHandler : subjectTypeHandlerList) {
            handlerMap.put(subjectTypeHandler.getHandlerType(), subjectTypeHandler);
        }

    }
}
